package service

import (
	"context"
	"encoding/json"
	"time"

	"fmt"

	"video-service/basic/config"
	__ "video-service/basic/proto"
	"video-service/handler/model"
)

type Server struct {
	__.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) GetUsernameByUsername(_ context.Context, in *__.GetUsernameByUsernameReq) (*__.GetUsernameByUsernameResp, error) {
	var user model.User
	if err := user.GetUsername(config.DB, in.Username); err != nil {
		return nil, err
	}
	return &__.GetUsernameByUsernameResp{
		Password: user.Password,
		UserId:   int64(user.ID),
	}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *Server) CreateUser(_ context.Context, in *__.CreateUserReq) (*__.CreateUserResp, error) {
	user := model.User{
		Username: in.Username,
		Password: in.Password,
	}
	if err := user.CreateUser(config.DB); err != nil {
		return nil, err
	}
	return &__.CreateUserResp{
		UserId: int64(user.ID),
	}, nil
}
func (s *Server) VideoList(_ context.Context, in *__.VideoListReq) (*__.VideoListResp, error) {
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.PageSize
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var video []model.VideoType
	query :=
		config.DB.Model(&model.Video{}).
			Select("videos.user_id,videos.title,videos.image,videos.price,videos.vip_price,videos.video_num,types.typename").
			Joins("left join types on videos.type_id = types.id").
			Offset(int(offset)).Limit(int(pageSize)).Where("status=?", in.Status)

	query.Find(&video)
	if in.Status == 1 {
		return nil, fmt.Errorf("该视频已隐藏")
	}
	var videolist []*__.VideoList
	for _, m := range video {
		list := __.VideoList{
			UserId:   m.UserId,
			Title:    m.Title,
			Image:    m.Image,
			VipPrice: m.VipPrice,
			VideoNum: m.VideoNum,
			Typename: m.Typename,
		}
		videolist = append(videolist, &list)
	}
	result, err := config.Rdb.Get(config.Ctx, "videolist").Result()
	if err == nil {
		err = json.Unmarshal([]byte(result), &videolist)
		if err != nil {
			return nil, err
		}
	} else {
		marshal, _ := json.Marshal(videolist)
		config.Rdb.Set(config.Ctx, "videolist", marshal, time.Minute*5)
	}

	return &__.VideoListResp{
		List: videolist,
	}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *Server) VideoDetail(_ context.Context, in *__.VideoDetailReq) (*__.VideoDetailResp, error) {
	videolist := fmt.Sprintf("videolist:%d", in.Id)

	var video model.Video
	marshal, err := json.Marshal(video)
	config.Rdb.SetNX(config.Ctx, "videolist", marshal, time.Minute*5)
	err = config.DB.Where("id=?", in.Id).First(&video).Error
	if err != nil {
		return nil, err
	}
	json.Unmarshal([]byte(videolist), &video)

	config.DB.Delete(videolist)
	return &__.VideoDetailResp{
		UserId:   video.UserId,
		Title:    video.Title,
		Image:    video.Image,
		VipPrice: video.VipPrice,
		VideoNum: video.VideoNum,
		TypeId:   video.TypeId,
	}, nil
}
func (s *Server) CollectVideo(_ context.Context, in *__.CollectVideoReq) (*__.CollectVideoResp, error) {
	collect := model.Collect{
		UserId:  in.UserId,
		VideoId: in.VideoId,
	}
	err := config.DB.Create(&collect).Error
	if err != nil {
		return nil, err
	}

	return &__.CollectVideoResp{
		CollectId: int64(collect.ID),
	}, nil
}
